<template>
  <div>
    <div style="display: inline-block;font-size:18px;margin-bottom: 15px;">
      <a href="#" @click="prev" style="text-decoration:none;font-size: 14px;">
        <icon-svg name="jiantou" style="width: 1.2em;height: 1.2em;position: relative;top: 0.3em;"></icon-svg>
        返回
      </a>
      <span style="display: inline-block;margin: 0 15px;color: #D9D9D9;">|</span>
      <span>区域地图</span>
    </div>
    <div>
      <div style="position: relative;display: inline-block;">
        <span>地址名称：</span>
        <el-input style="width: 200px;" @keydown.enter.native="phoneSelect" placeholder="请输入地址名称" v-model="conters">
        </el-input>&nbsp;&nbsp;
      </div>
      <el-button style="margin-left:15px;" size="mini" type="primary" icon="document"
        @click="phoneSelect">查询</el-button>
      <el-button style="margin-left:15px;" size="mini" type="primary" icon="document"
        @click="drawing_polygon">绘制地图图形</el-button>
      <el-button style="margin-left:15px;" size="mini" type="primary" plain icon="document"
        @click="clear">清空图形</el-button>
      <el-button style="margin-left:15px;" size="mini" type="warning" icon="document" @click="queren">确认添加</el-button>
      <el-button v-if="parentIdY!=0&&parentIdY!=-2" style="margin-left:15px;" size="mini" type="warning" icon="document" @click="tongbu">同步上级区域</el-button>
      <div v-if="parentIdY!=0&&parentIdY!=-2" style="color: darkorange;margin: 5px;">* 添加/修改二级区域时，请在红色虚线内绘制地图</div>
      <div id="container"></div>
    </div>


    <div id="toolControl">
      <div class="toolItem" id="polygon" title="多边形"></div>
    </div>
    <div>
      绘制：鼠标左键点击及移动即可绘制图形
      <br />
      结束绘制：鼠标左键双击即可结束多边形会自动闭合；单击即可结束
      <br />
      中断：绘制过程中按下esc键可中断该过程
    </div>
    <!-- 确认弹框 -->
    <el-dialog title="其他信息" :visible.sync="dialogFormVisibleU" center width="80%">
      <div style="position: relative;">
        <span style="width: 200px;display: inline-block;text-align: right;position: absolute;top: 0;">坐标集合：</span>
        <span style="width:50%;margin-left: 200px;position: relative;display: inline-block;">
          <div v-for="(item,index) in points" :key="index">纬度：{{item.lat}} 经度：{{item.lng}}</div>
        </span>
      </div>
      <div v-if="parentIdY==0||parentIdY==-2">
        <div v-if="parentIdY==-2&&parentIdE!=0">
          <div style="margin-bottom: 10px;">
            <span style="width: 200px;display: inline-block;text-align: right;">一口价：</span>
            <el-input style="width:50%;" v-model="baseMoney" type="text" placeholder="请输入一口价"></el-input>
          </div>
        </div>
        <div v-else>
          <div style="margin-bottom: 10px;" v-if="types==0">
            <span style="display: inline-block; width: 200px;text-align: right;">省份:</span>
            <el-select v-model="parentIdC" style="width:50%;" @change="handleChange()">
              <el-option v-for="item in citys" :key="item.id" :label="item.cityName" :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div style="margin-bottom: 10px;" v-if="types==0">
            <span style="display: inline-block; width: 200px;text-align: right;">代理城市:</span>
            <el-select v-model="cityId" style="width:50%;" :disabled="parentIdC==''">
              <el-option v-for="item in citys2" :key="item.id" :label="item.cityName" :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div style="margin-bottom: 10px;">
            <span style="display: inline-block; width: 200px;text-align: right;">范围地区：</span>
            <el-cascader style="width:50%" size="large" :options="options" ref="cascaderAddr" v-model="storeAddress"
              :placeholder="storeAddre" @change="handleChange55" :value="storeAddre">
            </el-cascader>
          </div>
        </div>

      </div>
      <div style="margin-bottom: 10px;" v-else>
        <span style="width: 200px;display: inline-block;text-align: right;">一口价：</span>
        <el-input style="width:50%;" v-model="baseMoney" type="text" placeholder="请输入一口价"></el-input>
      </div>

      <div style="margin-bottom: 10px;">
        <span style="width: 200px;display: inline-block;text-align: right;">是否启用：</span>
        <el-radio-group v-model="isEnable">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </div>
      <div style="margin-bottom: 10px;">
        <span style="width: 200px;display: inline-block;text-align: right;">备注：</span>
        <el-input style="width:50%;" v-model="remarks" type="textarea" :rows="2" placeholder="请输入备注"></el-input>
      </div>


      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleU = false">取 消</el-button>
        <el-button type="primary" @click="StairNoticeToU()">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  var map; // 地图
  var editor; // 编辑器
  var activeType = 'marker'; // 激活的图形编辑类型

  // // 切换激活图层
  // document.getElementById('toolControl').addEventListener('click', (e) => {
  // 	var id = e.target.id;
  // 	if (id !== 'toolControl') {
  // 		document.getElementById(activeType).className = 'toolItem';
  // 		document.getElementById(id).className = 'toolItem active';
  // 		activeType = id;

  // 		editor.setActiveOverlay(id);
  // 	}
  // });


  import {
    jsonp
  } from 'vue-jsonp'
  import {
    provinceAndCityData,
    regionData,
    provinceAndCityDataPlus,
    regionDataPlus,
    CodeToText,
    TextToCode
  } from 'element-china-area-data'
  var geocoder, map, markersArray, infoWindow = [];
  var editor; // 编辑器
  var activeType = 'marker'; // 激活的图形编辑类型
  export default {
    data() {
      return {

        // 地图相关
        longitude: '', //经度
        latitude: '', //维度

        options: regionData,
        points: [],
        points1: [],
        isEnable: 1,
        remarks: '',
        areaId: '',
        dialogFormVisibleU: false,
        conters: '',
        province: '', //省
        city: '',
        district: '', //区
        storeAddress: [],
        storeAddre: '请选择城市',

        parentIdC: '',
        citys: [],
        citys2: [],
        cityId: '',
        types: 0,
        parentIdE: 0,
        parentIdY: 0,
        baseMoney:'',
      }
    },
    methods: {
      // 返回上一级
      prev() {
        this.$router.back()
      },
      drawing_polygon() {
        editor.setActiveOverlay("polygon");
        console.log('-------------------', editor.getSelectedList("polygon"));
        //参数中的"polygon133"即为要进行编辑的MultiPolygon的id（注意方代码有定义）
      },
      //位置信息在地图上展示
      setMap() {
        console.log('地图定位：', this.longitude, this.latitude, )
        var center = new TMap.LatLng(this.latitude, this.longitude);
        if (map) {
          map.destroy();
        }
        map = []
        infoWindow = []
        // 初始化地图
        map = new TMap.Map('container', {
          zoom: 17, // 设置地图缩放级别
          pitch: 30,
          center: center, // 设置地图中心点坐标
          // mapStyleId: "style1", //个性化样式
          baseMap: {
            type: 'vector',
            // features: ['base', 'building3d'], // 隐藏矢量文字
          },
        });

        // --------------
        // 展示区域范围方法
        if (this.parentIdY != 0||this.parentIdY!=-2) {
          var polygonPath = this.points1
          var polygon = new TMap.MultiPolygon({
            map, // 显示多边形图层的底图
            styles: { // 多边形的相关样式
              'polygon': new TMap.PolygonStyle({
                'color': 'rgba(41,91,255,0.0)', // 面填充色
                'showBorder': true, // 是否显示拔起面的边线
                'borderColor': 'rgba(255,0,0,1)', // 边线颜色
                'borderWidth': 3, // 边线宽度
                'borderDashArray': [5, 5] // 虚线数组
              }),
            },
            geometries: [{
              id: 'polygon', // 多边形图形数据的标志信息
              styleId: 'polygon', // 样式id
              paths: polygonPath, // 多边形的位置信息
            }],
          });
        }

        // --------------

        // 初始化几何图形及编辑器
        console.log('new TMap.tools-------------', )
        var polygon = new TMap.MultiPolygon({
          map: map,
        });

        editor = new TMap.tools.GeometryEditor({
          // TMap.tools.GeometryEditor 文档地址：https://lbs.qq.com/webApi/javascriptGL/glDoc/glDocEditor
          map: map, // 编辑器绑定的地图对象
          overlayList: [
            // 可编辑图层 文档地址：https://lbs.qq.com/webApi/javascriptGL/glDoc/glDocEditor#4

            {
              overlay: polygon,
              id: 'polygon',
            },

          ],
          actionMode: TMap.tools.constants.EDITOR_ACTION.DRAW, // 编辑器的工作模式
          activeOverlayId: 'marker', // 激活图层
          snappable: true, // 开启吸附
        });

        if (this.points.length > 0) {
          var simplePath = this.points;
          console.log('======', simplePath)
          // 初始化几何图形及编辑器
          editor = new TMap.tools.GeometryEditor({
            map, // 编辑器绑定的地图对象
            overlayList: [ // 可编辑图层
              {
                overlay: new TMap.MultiPolygon({
                  map,
                  styles: {
                    highlight: new TMap.PolygonStyle({
                      color: 'rgba(255, 255, 0, 0.6)'
                    })
                  },
                  geometries: [{
                    paths: simplePath
                  }, ]
                }),
                id: 'polygon',
                selectedStyleId: 'highlight'
              }
            ],
            actionMode: TMap.tools.constants.EDITOR_ACTION.INTERACT, // 编辑器的工作模式
            activeOverlayId: 'polygon', // 激活图层
            selectable: true, // 开启点选功能
            snappable: true // 开启吸附
          });
        }


        // 监听绘制结束事件，获取绘制几何图形
        editor.on('draw_complete', (geometry) => {
          console.log('绘制的矩形定位的坐标：', geometry);
          this.points = geometry.paths
          console.log(geometry, 'this.points', this.points)
        });


      },
      // 查询
      phoneSelect() {
        // let searchInput = document.getElementById('searchInput').value; // 获取搜索内容
        // console.log(this.detailadd, this.detailadd.replace(/^\s+|\s+$/gm, ''))
        console.log(this.province + this.city + this.district + this.conters)

        if (this.detailadd == '') {
          this.$notify({
            title: '提示',
            duration: 1800,
            message: '请输入详细地址',
            type: 'warning'
          });
          return
        } else {
          var add = this.province + this.city + this.district + this.conters
          let that = this
          jsonp('https://apis.map.qq.com/ws/geocoder/v1/?address==' + add +
            '&key=DSQBZ-5MM3P-HEODO-VG6IX-SBRJE-PSBNX&get_poi=1&output=jsonp', {
              myCustomUrlParam: 'veryNice'
            }).then(response => {
            // handle success
            if (response.message == '查询无结果') {
              this.$notify({
                title: '提示',
                duration: 1800,
                message: '详细地址输入有误，请重新输入',
                type: 'warning'
              });
              return
            }
            console.log('response', response)
            that.longitude = response.result.location.lng; // 经度
            that.latitude = response.result.location.lat; // 纬度
            that.city = response.result.address_components.city;
            // that.detailadd = response.result.address_components.street
            // that.detailadd = response.result.address_components.province + response.result
            // 	.address_components.city + response.result.address_components.district + response.result.title
            that.setMap()
          }).catch(error => {
            // handle error
          }).then(() => {
            // always executed
          });
        }
      },

      // 清空
      clear() {
        console.log(this.longitude, '---', this.latitude, '-----')
        this.points = []
        this.setMap();
      },
      // 确认添加弹框
      queren() {
        // this.isEnable=1
        // this.remarks=''

        this.dataSelectCity()
        this.dialogFormVisibleU = true
      },
      StairNoticeToU() {
        if (this.points.length <= 0) {
          this.$notify({
            title: '提示',
            duration: 1800,
            message: '请输入区域定位',
            type: 'warning'
          });
          return
        }
        if (this.cityId == '') {
          this.$notify({
            title: '提示',
            duration: 1800,
            message: '请选择代理城市',
            type: 'warning'
          });
          return
        }
        if(this.parentIdY!=0&&this.parentIdY!=-2){
          if (this.baseMoney === '') {
            this.$notify({
              title: '提示',
              duration: 1800,
              message: '请输入一口价',
              type: 'warning'
            });
            return
          }

        }
        if(this.parentIdY==0||this.parentIdY==-2){
          if(this.parentIdE!=0){
            var datas = {}
                datas.points = this.points
                datas.isEnable =  this.isEnable
                datas.remarks =  this.remarks
                datas.areaId =  this.areaId
                datas.baseMoney = this.baseMoney
                datas.parentId = this.parentIdE
          }else{
            var datas = {}
                datas.points = this.points
                datas.isEnable = this.isEnable
                datas.remarks =  this.remarks
                datas.areaId = this.areaId
                datas.province = this.province
                datas.city =  this.city
                datas.district = this.district
                datas.cityId = this.cityId
          }

        }else{
          var datas = {}
              datas.points = this.points
              datas.isEnable =  this.isEnable
              datas.remarks =  this.remarks
              datas.areaId =  this.areaId
              datas.baseMoney = this.baseMoney
              datas.parentId = this.parentIdY
        }
        this.$http({
          url: this.$http.adornUrl('admin/banArea/saveBanArea'),
          method: 'post',
          // params: this.$http.adornParams({
          data: this.$http.adornData(datas)
        }).then(({
          data
        }) => {
          if (data.code == 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.dialogFormVisibleU = false
                this.$router.back()
              }
            })
          } else {
            this.$message({
              message: data.msg,
              type: 'warning',
              duration: 1500,
              onClose: () => {}
            })
          }
        })
      },
      // 获取省市区
      handleChange55(value) {
        value = this.$refs['cascaderAddr'].currentLabels
        this.province = value[0]
        this.city = value[1]
        this.district = value[2]
        if (this.city == '市辖区') {
          this.city = this.province
        }
      },
      // 获取城市省份列表
      dataSelectCity() {
        this.$http({
          url: this.$http.adornUrl('admin/cityInfo/getCityInfoList'),
          method: 'get',
          params: this.$http.adornParams({
            'parentId': 0,
            'cityName': '',
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            let returnData = data.data;
            this.citys = returnData.records
          }

        })
      },
      // 获取城市
      dataSelectCity2() {
        this.$http({
          url: this.$http.adornUrl('admin/cityInfo/getCityInfoList'),
          method: 'get',
          params: this.$http.adornParams({
            'parentId': this.parentIdC,
            'cityName': '',
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.citys2 = data.data.records
          }

        })
      },
      handleChange() {
        this.cityId = ''
        this.dataSelectCity2()
      },
      // 同步上级区域
      tongbu(){


        this.points = this.points1
        this.longitude = this.points[0].lng
        this.latitude = this.points[0].lat
        this.setMap();
      }
    },
    mounted() {



      if (this.$route.query.contexts) {
        this.types = 1
        var arr = JSON.parse(this.$route.query.contexts).points
        console.log('JSON.parse(this.$route.query.contexts)', JSON.parse(this.$route.query.contexts))
        this.isEnable = Number(JSON.parse(this.$route.query.contexts).isEnable)
        this.remarks = JSON.parse(this.$route.query.contexts).remarks
        // this.areaId = JSON.parse(this.$route.query.contexts).areaId
        this.province = JSON.parse(this.$route.query.contexts).province
        this.city = JSON.parse(this.$route.query.contexts).city
        this.district = JSON.parse(this.$route.query.contexts).district
        this.cityId = JSON.parse(this.$route.query.contexts).cityId
        this.parentIdE = JSON.parse(this.$route.query.contexts).parentId
		this.parentIdE = Number(this.parentIdE)
        this.baseMoney = JSON.parse(this.$route.query.contexts).baseMoney
        if (this.$route.query.parentId) {
          this.parentIdY = Number(this.$route.query.parentId)
          if(this.parentIdY==-1||this.parentIdY==-2){
            this.areaId = JSON.parse(this.$route.query.contexts).areaId
          }else{
            this.areaId = ''
          }

        }
        // if(this.parentIdE==0){
        //   this.areaId = ''
        //   // this.areaId = JSON.parse(this.$route.query.contexts).areaId
        // }else{
        //   this.areaId = ''
        // }

        this.storeAddress = []
        this.storeAddre = this.province + '/' + this.city + '/' + this.district
        if (arr.length > 0) {
          var contexts = JSON.parse(this.$route.query.contexts)
          this.points = []
          this.points1 = []
          console.log('-------this.areaId',this.areaId)
          console.log('------------this.parentIdY',this.parentIdY)
          console.log('------------------this.parentIdE',this.parentIdE)
          for (var i in contexts.points) {
            var obj = new TMap.LatLng(contexts.points[i].lat, contexts.points[i].lng)
            if (this.parentIdY == 0||this.parentIdY==-2) {
              this.points.push(obj)
              this.points1 = []
            }  else {
              this.points1.push(obj)
              this.points = []
            }


            this.longitude = contexts.points[0].lng
            this.latitude = contexts.points[0].lat
            console.log('`````````', obj, this.isEnable, this.remarks)
          }
        }
      } else {
        this.types = 0
        this.points = []
        this.points1 = []
        this.isEnable = 1
        this.remarks = ''
        this.areaId = ''
        this.province = ''
        this.city = ''
        this.district = ''
        this.cityId = ''
        this.parentIdC = ''
        this.storeAddress = []
        this.storeAddre = '请选择省市区'
        // this.parentId = 0
      }
      if(this.longitude==''){
        let data = {
          key: "ZBABZ-ZWECU-UQTVV-4LYDR-COK3F-5SF75", //申请的密钥
          output: "jsonp",
        };
        let url = "https://apis.map.qq.com/ws/location/v1/ip"
        this.$jsonp(url, data).then(res => {
          console.log('获取Ip定位成功----', res.result)
          this.longitude = res.result.location.lng
          this.latitude = res.result.location.lat
          this.province = res.result.ad_info.province
          this.city = res.result.ad_info.city
          this.district = res.result.ad_info.district
          this.setMap();
        }).catch(err => {
          this.$toast('获取Ip定位失败--', err.message)
        })
      }
      if (this.$route.query.parentId) {
        this.parentIdY = Number(this.$route.query.parentId)
				// if(this.parentIdY==0||this.parentIdY==-2){
				// 	this.types = 0
				// }else{
				// 	this.types = 2
				// }
      }
      console.log(this.parentIdY, '---------------------', this.latitude, )
	  
	  console.log('------------this.parentIdY',this.parentIdY)
	  console.log('------------------this.parentIdE',this.parentIdE)
      // this.getMyLocation()
      // this.dataSelect()
      this.setMap();

    }
  }
</script>

<style>
  /* html,
	body {
		height: 100%;
		margin: 0px;
		padding: 0px;
	} */

  #container {
    width: 100%;
    height: 80%;
  }

  #toolControl {
    position: absolute;
    top: 10px;
    left: 0px;
    right: 0px;
    margin: auto;
    width: 252px;
    z-index: 1001;
    display: none;
  }

  .toolItem {
    width: 40px;
    height: 40px;
    float: left;
    margin: 1px;
    padding: 4px;
    border-radius: 3px;
    background-size: 30px 30px;
    background-position: 4px 4px;
    background-repeat: no-repeat;
    box-shadow: 0 1px 2px 0 #e4e7ef;
    background-color: #ffffff;
    border: 1px solid #ffffff;
  }

  .toolItem:hover {
    border-color: #789cff;
  }

  .active {
    border-color: #d5dff2;
    background-color: #d5dff2;
  }

  #marker {
    background: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/marker_editor.png') 100% 100%;
  }

  #polyline {
    background: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/polyline.png') 100% 100%;
  }

  #polygon {
    background: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/polygon.png') 100% 100%;
  }

  #circle {
    background: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/circle.png') 100% 100%;
  }

  #rectangle {
    background: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/rectangle.png') 100% 100%;
  }

  #ellipse {
    background: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/ellipse.png') 100% 100%;
  }
</style>
